package com.cloudwise.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.system.UserInfo;
import com.alibaba.fastjson.JSON;
import com.cloudwise.entity.Userinfo;
import com.cloudwise.service.UserInfoService;
import com.cloudwise.service.impl.UserInfoServiceImpl;
import com.cloudwise.util.MyReturn;
import com.cloudwise.util.ProxyDynamicInterface;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2021/9/16 11:35
 * @description：用户控制器
 * @modified By：
 * @version: 1.0
 */
@WebServlet(urlPatterns = "/userAjax")
public class UserInfoAjaxServlet extends HttpServlet {
    //获取日志对象
    Logger logger = Logger.getLogger(UserInfoAjaxServlet.class);
    UserInfoService userInfoService=new UserInfoServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、设置请求和响应的编码格式
/*        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");*/
        //2、获取所有的参数，封装到map中
        //定义一个map集合封装所有的参数名和值
        HttpSession httpSession = req.getSession();

        Map<String,Object> map = new HashMap();
        //获取所有的参数名集合
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()){
            String parameterName = parameterNames.nextElement();
            map.put(parameterName, req.getParameter(parameterName));
        }
        /**
         * /user？method=add
         * 	添加 /user？method=add
         * 	删除/user？method=delete
         * 	修改/user？method=update
         * 	查询/user？method=find
         */
        //3、判断method参数的值
        String method=map.get("method")+"";
        MyReturn<List<Userinfo>> myReturn= new MyReturn();
        switch (method){
            case "add":
                break;
            case "delete":
                //使用动态代理堆删除操作进行增强处理，判断是否是admin
                ProxyDynamicInterface<UserInfoService> proxyDynamicInterface= new ProxyDynamicInterface(userInfoService,httpSession);
                userInfoService= proxyDynamicInterface.getProxyObj();
                userInfoService.deleteUserById(Integer.parseInt(map.get("id").toString()));
                /*//Object sessionUseranme = req.getSession().getAttribute("sessionUseranme");
                if(sessionUseranme!=null&& sessionUseranme.equals("admin")){
                    System.out.println("操作合法");
                }else
                {
                    System.out.println("权限不足");
                }*/

                break;
            case "update":
                break;
            case "findUserById":
                //按照id查询用户信息
                int  id = Integer.parseInt(map.get("id").toString()) ;
                Map<String, Object> user = userInfoService.findUserById(id);
                Object username = user.get("username");
                //设置响应数据的格式
                resp.setContentType("text/html");
                resp.getWriter().write(username.toString());
                break;
            case "findPhoneByUsername":
                //按照用户名查询用户信息
                String  usernameNew = map.get("username").toString();
                Map<String, Object> user1 = userInfoService.findUserByUserName(usernameNew);
                Object phone = user1.get("phone");
                resp.getWriter().write(phone.toString());
                break;
            default:
                //查询所有的用户
                if(!map.containsKey("pageNo")){

                    map.put("pageNo",map.get("page"));
                }
                if(!map.containsKey("pageSize")){

                    map.put("pageSize",map.get("limit"));
                }
                List<Map<String, Object>> allUserInfo = userInfoService.findAllUserInfo(map);
               //将list<map>转换成list<userinfo>
                List<Userinfo> list = Convert.convert(new TypeReference<List<Userinfo>>() {}, allUserInfo);
                myReturn.setCode(0);
                //设置总条数
                int allCount = userInfoService.findAllCount();
                myReturn.setCount(allCount);
                myReturn.setData(list);
                break;

        }

        //设置响应数据的格式
        resp.setContentType("application/json");
        //将实体对象转换成json字符串回传
        String jsonString = JSON.toJSONString(myReturn);
        resp.getWriter().write(jsonString);

    }
}
